var express = require('express');
var router = express.Router();
//var mongoose = require('mongoose');
//var Cat = mongoose.model('Cat', { name: String });
var path = require('path');
var multiparty = require('multiparty');
var fs = require('fs');

var multer = require('multer');

/* GET home page. */
router.get('/', function(req, res, next) {
//	var kitty = new Cat({ name: 'hello world' });
//	kitty.save(function (err) {
//	  if (err) {
//	    console.log(err);
//	  } else {
//	    console.log('mongoose db success');
//	  }
//	});
    res.render('index', { title: 'Express' });
});

//设置参数
var storage = multer.diskStorage({
    destination: function (req, file, cb) {  //存储路径
      cb(null, './uploads')
    },
    filename: function (req, file, cb) {  //设置文件名
      cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})
//实例化
var upload = multer({ storage: storage })

router.post('/upload', function(req, res,next) {
    var upload = multer({
        storage:storage,
        fileFilter:function(req,file,callback){
            var ext = path.extname(file.originalname);
            if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif'){
                return callback(res.end('文件类型不符合'));
            }
            callback(null,true);
        }
    }).single('avatar');

    upload(req,res,function(err){
        res.end('file upload');
    })
})

router.post('/uploadImg', function(req, res,next) {
    var form = new multiparty.Form();
    //设置编码
    form.encoding = 'utf-8';
    //设置文件存储路径
    form.uploadDir = './uploadtemp';
    //设置文件大小限制
    form.maxFilesSize = 2 * 1024 * 1024;  //大小不能超过2M
    var saveUrl = "http://localhost:3000/";

    form.parse(req,function(err,fields,files){
        var uploadurl = './images/upload/';
        file = files['filedata'];  //传递过来一个文件
        originalFilename = file[0].originalFilename; // 原始文件名
        tmpPath = file[0].path;  //设置路径

        var timestamp = new Date().getTime();
        uploadurl += timestamp + originalFilename;  //设置上传文件的路径
        newPath = './public/' + uploadurl;  //最终的文件上传路径

        var fileReadStream = fs.createReadStream(tmpPath);
        var fileWriteStream = fs.createWriteStream(newPath);
        fileReadStream.pipe(fileWriteStream); //管道流
        fileWriteStream.on('close',function(){
            fs.unlinkSync(tmpPath);   //unlink是文件删除操作
            res.send('{"err":"","msg":"'+uploadurl+'"}');
        })
    });
});


module.exports = router;
